package cn.easyplatform.studio.web.views.impl;

import cn.easyplatform.lang.Strings;
import cn.easyplatform.studio.utils.WebUtils;
import cn.easyplatform.studio.vos.ElementVo;
import cn.easyplatform.studio.web.editors.Editor;
import cn.easyplatform.studio.web.editors.EditorCallback;
import cn.easyplatform.studio.web.editors.help.GuideConfigEditor;
import cn.easyplatform.web.ext.introJs.Action;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Page;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ActionView extends AbstractView<List<Action>> {
    private Borderlayout borderLayout;
    private Listbox listbox;

    private boolean isChange = false;
    private List<Action> currentActionList;
    private List<Action> actionList;
    private GuideConfigEditor.GuideConfigType type;
    /**
     * @param cb
     */
    protected ActionView(EditorCallback<List<Action>> cb, List<Action> actionList,
                         GuideConfigEditor.GuideConfigType type, Component component) {
        super(component, cb);
        List<Action> actions = new ArrayList<>();
        for (Action action: actionList) {
            Action newAction = new Action(action.getActionCompId(), action.getActionEvent(), action.getActionValue());
            actions.add(newAction);
        }
        this.currentActionList = actionList;
        this.actionList = actions;
        this.type = type;
    }

    @Override
    protected void createContent(Component parent) {
        borderLayout = new Borderlayout();
        North north = new North();
        north.setSize("38px");
        north.setHflex("1");
        north.setBorder("none");
        north.setParent(borderLayout);

        Hlayout northDiv = new Hlayout();
        northDiv.setVflex("1");
        northDiv.setHflex("1");
        northDiv.setParent(north);

        String[] iconSclass = new String[]{"z-icon-plus", "z-icon-indent", "z-icon-minus",
                "z-icon-arrow-up", "z-icon-arrow-down"};
        String[] label = new String[]{"entity.table.add", "entity.table.insert", "entity.table.del",
                "entity.table.up", "entity.table.down"};
        String[] id = new String[]{"addField", "insertField", "deleteField",
                "moveUp", "moveDown"};
        for (int index = 0; index < iconSclass.length; index++) {
            A field = new A();
            field.setIconSclass(iconSclass[index]);
            field.setLabel(Labels.getLabel(label[index]));
            field.setSclass("btn btn-light btn-sm");
            field.setId(id[index]);
            field.addEventListener(Events.ON_CLICK, this);
            field.setParent(northDiv);
        }

        Center center = new Center();
        center.setHflex("1");
        center.setVflex("1");
        center.setBorder("none");
        center.setParent(borderLayout);

        listbox = new Listbox();
        listbox.setHflex("1");
        listbox.setVflex("1");
        listbox.setCheckmark(true);
        listbox.setOddRowSclass("none");
        listbox.setMold("paging");
        listbox.getPagingChild().setMold("os");
        listbox.setParent(center);

        Listhead listhead = new Listhead();
        listhead.setSizable(true);
        listhead.setParent(listbox);

        Listheader selectedHeader = new Listheader();
        selectedHeader.setWidth("25px");
        selectedHeader.setParent(listhead);
        String[] labels = new String[]{"guide.step.element", "button.event", "action.value"};
        for (int index = 0; index < labels.length; index++) {
            Listheader listheader = new Listheader();
            listheader.setLabel(Labels.getLabel(labels[index]));
            listheader.setHflex("1");
            listheader.setParent(listhead);
        }

        if (actionList.size() > 0) {
            for (int index = 0; index < actionList.size(); index++) {
                createAction(actionList.get(index), index);
            }
        }
        South south = new South();
        south.setSize("44px");
        south.setHflex("1");
        south.setBorder("none");
        south.setParent(borderLayout);

        Div southDiv = new Div();
        southDiv.setParent(south);

        Button save = new Button(Labels.getLabel("button.save"));
        save.setIconSclass("z-icon-save");
        save.setSclass("pull-right epstudio-top");
        save.setId("save");
        save.addEventListener(Events.ON_CLICK, this);
        save.setParent(southDiv);

        borderLayout.setParent(parent);
    }
    private Listitem createAction(Action action, int pos) {
        Listitem li = new Listitem();
        li.setValue(action);
        li.appendChild(new Listcell());

        Textbox compId;
        compId = new Bandbox();
        compId.setHflex("1");
        compId.setReadonly(true);
        compId.setValue(action.getActionCompId());
        Listcell elementCell = new Listcell();
        elementCell.appendChild(compId);
        li.appendChild(elementCell);

        Combobox eventBox = new Combobox();
        Textbox eventName = new Textbox();
        /*if (type == GuideConfigEditor.GuideConfigType.GuideConfigApp) {

        } else {
            eventName.setValue(action.getActionEvent());
            eventName.setHflex("1");
            //eventName.setReadonly(true);
            Listcell valueCell = new Listcell();
            valueCell.appendChild(eventName);
            li.appendChild(valueCell);
        }*/
        eventBox.setHflex("1");
        eventBox.setReadonly(false);
        String[] positionType = new String[]{Events.ON_CLICK, Events.ON_RIGHT_CLICK, Events.ON_DOUBLE_CLICK, Events.ON_OK,
                Events.ON_CANCEL, Events.ON_CHANGE, Events.ON_CHANGING, Events.ON_SELECT, Events.ON_CHECK, Events.ON_OPEN
                , Events.ON_CLOSE, Events.ON_UPLOAD};
        List<String> positionTypeList = Arrays.asList(positionType);
        for (int index = 0; index < positionTypeList.size(); index++) {
            Comboitem ci = new Comboitem();
            ci.setLabel(positionTypeList.get(index));
            ci.setValue(positionTypeList.get(index));
            ci.setParent(eventBox);
            if (Strings.isBlank(action.getActionEvent()) == false && action.getActionEvent().equals(positionTypeList.get(index)))
                eventBox.setSelectedIndex(index);
        }
        Listcell eventCell = new Listcell();
        eventCell.appendChild(eventBox);
        li.appendChild(eventCell);

        Textbox value = new Textbox(action.getActionValue());
        value.setHflex("1");
        Listcell valueCell = new Listcell();
        valueCell.appendChild(value);
        li.appendChild(valueCell);
        if (pos >= 0) {
            listbox.getItems().add(pos, li);
        } else
            li.setParent(listbox);

        new ActionCell(compId, eventBox, value, eventName);

        return li;
    }
    private void moveAction(boolean down) {
        Listitem item = listbox.getSelectedItem();
        Action action = item.getValue();
        int pos = listbox.getSelectedIndex();
        if (down)
            pos++;
        else
            pos--;
        if (pos < 0)
            pos = 0;
        else if (pos >= listbox.getItemCount())
            pos = listbox.getItemCount() - 1;
        item.detach();
        listbox.getItems().add(pos, item);
        actionList.remove(action);
        actionList.add(pos, action);
    }
    @Override
    public void onEvent(Event event) throws Exception {
        if (event.getTarget().getId().equals("addField")) {
            Action action = new Action();
            if (actionList == null)
                actionList = new ArrayList<>();
            actionList.add(action);
            Listitem row = createAction(action, -1);
            listbox.setActivePage(row);
            isChange = true;
        } else if (event.getTarget().getId().equals("insertField")) {
            if (listbox.getSelectedItem() == null) {
                WebUtils.showError(Labels.getLabel("action.selected.error"));
                return;
            }
            int pos = listbox.getSelectedIndex();
            Action action = new Action();
            if (actionList == null)
                actionList = new ArrayList<>();
            if (pos >= 0) {
                pos++;
                actionList.add(pos, action);
            } else
                actionList.add(action);
            createAction(action, pos);
            isChange = true;
        } else if (event.getTarget().getId().equals("deleteField")) {
            if (listbox.getSelectedItem() != null)
                WebUtils.showConfirm(Labels.getLabel("button.delete"), this);
            else
                WebUtils.showError(Labels.getLabel("action.selected.error"));
        } else if (event.getTarget().getId().equals("moveUp")) {
            if (listbox.getSelectedItem() != null) {
                moveAction(false);
                isChange = true;
            } else
                WebUtils.showError(Labels.getLabel("action.selected.error"));
        } else if (event.getTarget().getId().equals("moveDown")) {
            if (listbox.getSelectedItem() != null) {
                moveAction(true);
                isChange = true;
            } else
                WebUtils.showError(Labels.getLabel("action.selected.error"));
        } else if (event.getName().equals(Events.ON_OK)) {// 删除栏位
            Action action = listbox.getSelectedItem().getValue();
            actionList.remove(action);
            listbox.getSelectedItem().detach();
            isChange = true;
        } else if (event.getTarget().getId().equals("save")) {
            if (isChange == false) {
                cb.setValue(currentActionList);
                borderLayout.getRoot().detach();
                onCloseClick(win);
            }
            else
                save();
        }
    }

    private void save() {
        Boolean canSave = true;
        for (Action action : actionList) {
            if (Strings.isBlank(action.getActionCompId())) {
                canSave = false;
            }
        }
        if (canSave == true) {
            cb.setValue(actionList);
            borderLayout.getRoot().detach();
            onCloseClick(win);
        }
        else
            WebUtils.showError(Labels.getLabel("message.no.empty", new Object[]{Labels.getLabel("guide.step.element")}));

    }

    private class ActionCell implements EventListener<Event> {

        private Bandbox compId;
        private Combobox eventCombobox;
        private Textbox value;


        public ActionCell(Textbox compId, Combobox eventCombobox, Textbox value, Textbox eventName) {
            this.compId = (Bandbox) compId;
            this.compId.addEventListener(Events.ON_OK, this);
            this.compId.addEventListener(Events.ON_CHANGE, this);
            this.compId.addEventListener(Events.ON_OPEN, this);
            this.eventCombobox = eventCombobox;
            this.eventCombobox.addEventListener(Events.ON_CHANGE, this);
            this.value = value;
            this.value.addEventListener(Events.ON_CHANGE, this);
            this.value.addEventListener(Events.ON_OPEN, this);
        }

        @Override
        public void onEvent(Event event) throws Exception {
            Listitem listitem = (Listitem) compId.getParent().getParent();
            final Action index = listitem.getValue();
            if (event.getTarget().equals(compId)) {
                AbstractView.createElementView(new EditorCallback<ElementVo>() {
                    @Override
                    public ElementVo getValue() {
                        return null;
                    }

                    @Override
                    public void setValue(ElementVo value) {
                        isChange = true;
                        compId.setValue(value.getElementId());
                        index.setActionCompId(value.getElementId());
                    }

                    @Override
                    public String getTitle() {
                        return Labels.getLabel("guide.step.element");
                    }

                    @Override
                    public Page getPage() {
                        return compId.getPage();
                    }

                    @Override
                    public Editor getEditor() {
                        return null;
                    }
                }, type, compId).doOverlapped();
            } else if (event.getTarget().equals(eventCombobox)) {
                isChange = true;
                String valueStr = null;
                if (eventCombobox.getSelectedItem() != null)
                    valueStr = eventCombobox.getSelectedItem().getValue();
                index.setActionEvent(valueStr);
            } else if (event.getTarget().equals(value)) {
                isChange = true;
                index.setActionValue(value.getValue());
            }
        }
    }
}
